﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using Boomerang.Common.Configuration;
using System.Threading;

namespace Boomerang.Management.UIControlers
{
    public class ConfigurationGridViewController
    {
        private string[] cols = new string[] { "Organization Name", "Authentication Mode", "Boomerang User", "Discovery Server Url" };

        private DataGridView grid;

        public ConfigurationGridViewController(DataGridView grid)
        {
            this.grid = grid;

            grid.Rows.Clear();
            grid.AutoGenerateColumns = false;

            grid.Columns.Clear();

            foreach (string item in cols)
            {
                grid.Columns.Add(item.Replace(" ", ""), item);
                if (!item.Contains("Url"))
                    grid.Columns[item.Replace(" ", "")].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                else
                    grid.Columns[item.Replace(" ", "")].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            }
            
            grid.Columns.Add("Org", "Org");
            grid.Columns["Org"].Visible = false;
            

            PopulateColumns();

            ConfigurationManager.OnConfigurationChange += new ConfigurationChangeEventHandler(ConfigurationManager_OnConfigurationChange);            
        }

        private void PopulateColumns()
        {
            if (grid.InvokeRequired)
            {
                grid.Invoke(new ThreadStart(delegate() { PopulateColumns(); }), null);
                return;
            }
            grid.Rows.Clear();

            foreach (Organization org in ConfigurationManager.GetAllOrganizations())
            {
                grid.Rows.Add(new object[] { org.CrmConnectionOptions.OrgName,                
                org.CrmConnectionOptions.AuthMode.ToString(),
                org.SmsConnectionOptions.BoomerangUserName,
                org.CrmConnectionOptions.GetCrmDiscoveryServiceUrl(),
                org
                });
                
            }                        
        }

        void ConfigurationManager_OnConfigurationChange()
        {
            PopulateColumns();
        }

        public Organization GetSelected()
        {
            Organization result = null;
            if (grid.SelectedRows.Count >= 0)
            {
                result = (Organization) grid.SelectedRows[0].Cells[4].Value;
            }
            return result;
        }

    }
}
